var express = require('express');
var router = express.Router();
let {userModel} = require('../model/db')

const crypto = require('crypto');
const multer = require('multer');
const path = require('path');
const { releasemodel } = require('../model/db');

/* GET home page. */
router.get('/login',async function(req, res, next) {
  let user = await userModel.find()
  res.send({
    code:200,
    user
  })
});

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/'); // 保存路径
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = `${Date.now()}-${crypto.randomBytes(8).toString('hex')}`;
    cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`); // 文件名
  }
});

const upload = multer({ storage: storage });

router.post('/api/upload', upload.array('files[]'), (req, res) => {
  let imglist = []
  for(let i of req.files){
    imglist.push(`http://127.0.0.1:3000/${i.path}`)
  }
  res.send({
    code: 200,
    msg: '上传成功',
    imglist
  });
});

router.post('/addrelease', async (req, res) => {
  await releasemodel.create(req.body)
  res.send({
    code: 200,
    msg: '发布成功'
  })
})

router.get('/getrelease', async (req, res) => {
  let data = await releasemodel.find()
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
})

router.post('/getreleaseone', async (req, res) => {
  let {id} = req.body
  let data = await releasemodel.findOne({_id:id})
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
})

function authenticate(req, res, next) {
  // 这里应该包含你的认证逻辑，例如检查 JWT 或会话
  next(); // 如果认证成功，则调用 next()
}

router.post('/api/delete-images', authenticate, async (req, res) => {
  try {
    const { filenames } = req.body; // 假设前端发送的是一个文件名数组

    if (!Array.isArray(filenames) || filenames.length === 0) {
      return res.status(400).json({ error: 'Invalid or empty filenames array.' });
    }

    // 删除每个文件并收集结果
    const results = await Promise.all(
      filenames.map(async (filename) => {
        const filePath = path.join(__dirname, 'uploads', filename);

        try {
          // 检查文件是否存在
          await fs.access(filePath);
          // 删除文件
          await fs.unlink(filePath);
          return { filename, status: 'deleted' };
        } catch (error) {
          if (error.code === 'ENOENT') {
            return { filename, status: 'not found' };
          }
          throw error;
        }
      })
    );

    // 检查是否有任何错误
    const errors = results.filter(result => result.status !== 'deleted');
    if (errors.length > 0) {
      return res.status(207).json({ message: 'Some files were not deleted.', details: errors });
    }

    res.status(200).json({ message: 'All images deleted successfully.', details: results });
  } catch (error) {
    res.status(500).json({ error: 'An error occurred while deleting the files.' });
  }
});

router.post('/editrelease', async (req, res) => {
  let {id, ...a} = req.body
  console.log({...a})
  await releasemodel.updateOne({_id:id}, {...a})
  res.send({
    code: 200,
    msg: '修改成功'
  })
})

router.post('/editflag', async (req, res) => {
  let {id} = req.body
  let a = await releasemodel.findOne({_id: id})
  let data = {...a._doc}
  if(data.isFlag==='1'){
    data.isFlag='0'
  }else{
    data.isFlag='1'
  }
  await releasemodel.updateOne({_id: id}, {...data})
  res.send({
    code: 200
  })
})

module.exports = router;
